//
//  RootViewController.m
//  XYLBaiduMap2017
//
//  Created by 夏玉林 on 17/2/15.
//  Copyright © 2017年 夏玉林. All rights reserved.
//

#import "RootViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "HHXYLLocationPulseAnnotaionView.h"

//定位
#import "XYLPinView.h"
#import "XYLFenceMapAnnotationView.h"
//用户定位
#import "XYLLocationAnnotationView.h"
#import "XYLNearlyFreindPinView.h"
#import "XYLPaoPaoView.h"

#import "XYLFindFreidlyModle.h"

#import "UIImageView+WebCache.h"

#import "BMKClusterManager.h"//点聚合管理类
#import "XYLClusterAnnotation.h"
#import "XYLClusterAnnotationView.h"

@interface RootViewController ()<BMKMapViewDelegate,CLLocationManagerDelegate>

@property (nonatomic,assign)int count;

@property (nonatomic,strong)BMKMapView *mapView;

//!定位管理
@property (nonatomic, strong) CLLocationManager *locationManager;

//定位点
@property (nonatomic, assign)CLLocationCoordinate2D coordinate2D;
//定位点数组
@property (nonatomic, strong)NSMutableArray *locationArray;

//用户定位点
@property (nonatomic, strong)XYLLocationAnnotationView *locationPointView;
//用户定位点
@property (nonatomic, assign)CLLocationCoordinate2D userCoordinate2D;
//用户定位点数组
@property (nonatomic, strong)NSMutableArray *userPointArray;

//实时的定位点
@property (nonatomic, strong)XYLPinView *locationPoint;
//周边用户在大头针
@property (nonatomic, strong)XYLNearlyFreindPinView *freidPinPoint;

//点聚合管理类
@property (nonatomic, strong)BMKClusterManager *clusterManager;//点聚合管理类

@property (nonatomic, assign)NSInteger clusterZoom;//聚合级别

@property (nonatomic, strong)NSMutableArray *clusterCashes;//点聚合缓存标注

@end

@implementation RootViewController

#pragma mark========初始化========
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.count = 0;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStatuLocation) name:@"HHFindViewController" object:nil];
    }
    return self;
}
#pragma mark========懒加载方法========
- (NSMutableArray *)userPointArray{
    if (!_userPointArray) {
        _userPointArray = [[NSMutableArray alloc] init];
    }
    return _userPointArray;
}
- (NSMutableArray *)locationArray{
    if (!_locationArray) {
        _locationArray = [[NSMutableArray alloc] init];
    }
    return _locationArray;
}
- (BMKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[BMKMapView alloc] init];
        _mapView.mapType = BMKMapTypeStandard;
        _mapView.zoomLevel = 21;
        _mapView.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);
    }
    return _mapView;
}
- (BMKClusterManager *)clusterManager{
    if (!_clusterManager) {
        _clusterManager = [[BMKClusterManager alloc] init];
    }
    return _clusterManager;
}

- (NSMutableArray *)clusterCashes{
    if (!_clusterCashes) {
        _clusterCashes = [[NSMutableArray alloc] init];
    }
    return _clusterCashes;
}

#pragma mark - ======================
- (CLLocationManager *)locationManager
{
    if (!_locationManager)
    {
        _locationManager = [[CLLocationManager alloc] init];
        
        _locationManager.delegate = self;
        // 设置定位精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 定位频率,每隔多少米定位一次
        _locationManager.distanceFilter = kCLDistanceFilterNone;
    }
    return _locationManager;
}
#pragma mark - =====================定位方法====================
- (void)locationAuthorizationStatus
{
    if (![CLLocationManager locationServicesEnabled])
    {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    // 如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted){
         NSLog(@"定位服务当前可能尚未打开，");
        [self.locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
         NSLog(@"，请设置打开！");
        [self.locationManager startUpdatingLocation];
    }
//    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways){
//        [self.locationManager startUpdatingLocation];
//    }
    
}

#pragma mark========视图进出方法========
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"百度地图";
    [self.view addSubview:self.mapView];
    //这句代码一定要有
    [self.locationManager startUpdatingLocation];
    
}
//添加用户在视图
- (void)updateClusters{
#if 0
    _userCoordinate2D.latitude = 22.51696641791897;
    _userCoordinate2D.longitude = 113.9480171593211;
    
    _freidPinPoint = [[XYLNearlyFreindPinView alloc] initWithCoordinate:_userCoordinate2D];
    [self.userPointArray addObject:_freidPinPoint];
    
    _freidPinPoint.title = @"";
    
    [_mapView addAnnotation:_freidPinPoint];
    [_mapView viewForAnnotation:_freidPinPoint].selected = YES;
#endif
   // [_mapView removeOverlays:self.userPointArray];
#if 0
    //因为数据多 取 前10个 测试
    for (NSInteger i =0;i <= 5  ;i++) {
        XYLFindFreidlyModle *model = self.base_dataArry[i];
        CLLocationCoordinate2D coordinate2D ;
        coordinate2D.latitude = [model.lat doubleValue];
        coordinate2D.longitude = [model.lon doubleValue];
         _freidPinPoint = [[XYLNearlyFreindPinView alloc] initWithCoordinate:coordinate2D];
        
         [self.userPointArray addObject:_freidPinPoint];
        
        _freidPinPoint.title = @"娇娇";
        
        [_mapView addAnnotation:_freidPinPoint];
        [_mapView viewForAnnotation:_freidPinPoint].selected = YES;
    }
#endif
    
#if 1
    //清空
    [self.clusterManager clearClusterItems];
    [self.clusterCashes removeAllObjects];
    
    for (NSInteger i = 3;i< 22 ;i++) {
        [self.clusterCashes addObject:[NSMutableArray array]];
    }
    
    //向点聚合管理类中添加标注
    
    for (NSInteger i =0;i <= 25  ;i++) {
        //添加经纬度
        XYLFindFreidlyModle *model = self.base_dataArry[i];
        CLLocationCoordinate2D coordinate2D ;
        coordinate2D.latitude = [model.lat doubleValue];
        coordinate2D.longitude = [model.lon doubleValue];
        
        //添加聚合标注
        BMKClusterItem *clusterItem = [[BMKClusterItem alloc] init];
        clusterItem.coor = coordinate2D;
        
        [self.clusterManager addClusterItem:clusterItem];
    }

    //聚合级别
    _clusterZoom = (NSInteger )_mapView.zoomLevel;
    
    @synchronized (self.clusterCashes) {
        __block NSMutableArray *clusters = [self.clusterCashes objectAtIndex:_clusterZoom - 3];
        
        if (clusters.count > 0) {
            [_mapView removeAnnotations:_mapView.annotations];
            [_mapView addAnnotations:clusters];
        }else
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                //获取聚合后的标注
                __block NSArray *array = [self.clusterManager getClusters:_clusterZoom];
                //回到主线程 刷新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    for (BMKCluster *item in array) {
                        XYLClusterAnnotation *annotation = [[XYLClusterAnnotation alloc] init];
                        annotation.coordinate = item.coordinate;
                        annotation.size = item.size;
                        annotation.title = [NSString stringWithFormat:@"我是%ld个", item.size];
                        
                        [clusters addObject:annotation];
                    }
                    
                    [_mapView removeAnnotations:_mapView.annotations];
                    
                    [_mapView addAnnotation:self.locationArray.firstObject];
                    
                    [_mapView addAnnotations:clusters];
                    
                });
                
            });
        }
        
    };
#endif
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    
   // [self  requestData];
    //写在这 自定义的大头针才有作用(不然有时会出现原生的大头针)
   // [self startAddAnnotationViewsWithUsers];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    
}
#pragma mark======私有方法=========
- (void)updateStatuLocation{
    NSLog(@"更改定位权限状态");
    if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
        XYLLog(@"使用");
        [self.locationManager startUpdatingLocation];
        
    }else{
        XYLLog(@"请开启定位权限");
    }
    
}
#pragma mark======网络请求方法=========
- (void)requestData{
    
    self.base_url = [SERVER_ADDRESS stringByAppendingString:@"app2/share/get_nearby_user_list"];
    
   NSString *log = [NSString stringWithFormat:@"%f",_coordinate2D.longitude];
   NSString *lat = [NSString stringWithFormat:@"%f",_coordinate2D.latitude];
  //  double log = [_coordinate2D.longitude double];
   
    double xyllog = [log doubleValue];
    double xyllat = [lat doubleValue];
    
    
    self.base_dic = @{@"lon":@(xyllog),@"lat":@(xyllat),@"radium":@(2000),@"tags":@"",@"gender":@"",@"gender":@""};
    
    [[XYLBaseRequest RequestGlobal] GetRequesetWithURL:self.base_url andParameters:self.base_dic completion:^(NSError *error, id obj) {
        if (obj) {
           // XYLLog(@"成功%@",obj);
            NSDictionary *dic = obj[@"data"];
            if (dic !=nil) {
                XYLLog(@"解析%@",dic);
                for (NSDictionary *data in dic[@"users"]) {
                    XYLFindFreidlyModle *model = [[XYLFindFreidlyModle alloc] init];
                    [model setValuesForKeysWithDictionary:data];
                    [self.base_dataArry addObject:model];
                }
                //添加大头针
                [self updateClusters];
            }
            
        }else{
            XYLLog(@"错误%@",error);
        }

    }];
}

#pragma mark=======原生定位代理回调==========
int XYLlocationFirstTag = 0;

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    [manager stopUpdatingLocation];
    
    XYLLog(@"定位成功＝＝＝%@",locations.firstObject);
    CLLocation *location = [locations firstObject];
    
    CLLocationCoordinate2D coordinate2D;
    
    _coordinate2D = location.coordinate;
    
     coordinate2D = BMKCoorDictionaryDecode(BMKConvertBaiduCoorFrom(location.coordinate, BMK_COORDTYPE_GPS));
    
    //_coordinate2D = coordinate2D;
    
    [_mapView setCenterCoordinate:coordinate2D];
    
    [_mapView removeAnnotations:self.locationArray];
    
    _locationPoint = [[XYLPinView alloc] initWithCoordinate:coordinate2D];
    _locationPoint.title = @"我是定位点";
    [self.locationArray removeAllObjects];
    [self.locationArray addObject:_locationPoint];
    
    [_mapView addAnnotation:_locationPoint];
    [_mapView viewForAnnotation:_locationPoint].selected = YES;
    
    if (XYLlocationFirstTag ==0) {
         //发起网络请求
        [self requestData];
        
        XYLlocationFirstTag = 1;
    }
    
}
#if 0
- (void)updateUserLocation:(CLLocationCoordinate2D )coor tags:(NSString *)tags gender:(NSInteger)gender constellation:(NSInteger)constellation radium:(CGFloat )radium{
    self.base_url = [SERVER_ADDRESS stringByAppendingString:@"app2/share/get_nearby_user_list"];
    
    NSString *log = [NSString stringWithFormat:@"%f",113.936421];
    NSString *lat = [NSString stringWithFormat:@"%f",22.514445];
    //  double log = [_coordinate2D.longitude double];
    
    self.base_dic = @{@"lon":log,@"lat":lat,@"radium":@(2000),@"tags":@"",@"gender":@"",@"gender":@""};
    
    [[XYLBaseRequest RequestGlobal] GetRequesetWithURL:self.base_url andParameters:self.base_dic completion:^(NSError *error, id obj) {
        if (obj) {
            // XYLLog(@"成功%@",obj);
            NSDictionary *dic = obj[@"data"];
            NSInteger i = 0;
            if (dic !=nil) {
                XYLLog(@"解析%@",dic);
                for (NSDictionary *data in dic[@"users"]) {
                    
                    XYLFindFreidlyModle *model = [[XYLFindFreidlyModle alloc] init];
                    [model setValuesForKeysWithDictionary:data];
                    [self.base_dataArry addObject:model];
                   
                }
                
                
                
                [self startAddAnnotationViewsWithUsers];
            }
            
        }else{
            XYLLog(@"错误%@",error);
        }
        
    }];

}
#endif

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if(status == kCLAuthorizationStatusAuthorizedWhenInUse){
         XYLLog(@"使用");
         [self.locationManager startUpdatingLocation];
        
    }else if(status == kCLAuthorizationStatusDenied){
         XYLLog(@"不使用");
         [self.locationManager requestWhenInUseAuthorization];
    }
    
}
- (void)locationManagerDidPauseLocationUpdates:(CLLocationManager *)manager{
    XYLLog(@"这是什么");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    XYLLog(@"定位失败");
}
#pragma mark==========地图的代理方法================
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
    
    typeof(self) weakSelf = self;
    
    //定位点的显示
    if ([annotation isKindOfClass:[XYLPinView class]]) {
        
        static NSString *identifier = @"currentLocation";
        
        XYLFenceMapAnnotationView *locationAnnotationView = (XYLFenceMapAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (!locationAnnotationView) {
            locationAnnotationView = [[XYLFenceMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
            locationAnnotationView.canShowCallout = NO;
        }
        return locationAnnotationView;
    }
    
#if 1
    else if ([annotation isKindOfClass:[XYLNearlyFreindPinView class]]) {
        
        static NSString *identifier = @"userLocation";
        self.count ++;
        
        XYLLocationAnnotationView *locationAnnotationView = (XYLLocationAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (!locationAnnotationView) {
            locationAnnotationView = [[XYLLocationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
            
        }
        locationAnnotationView.canShowCallout = NO;
        
        locationAnnotationView.index = self.count;//记录下标
        locationAnnotationView.clickBtnAnnotaionView.tag = self.count;
        
        locationAnnotationView.block = ^(UIButton *btn){
            [weakSelf  selectedAnnotationViewWithIndex:btn];
        };
        
        // 从天上掉下效果
        // 设置可拖拽
        locationAnnotationView.draggable = YES;
        //如果不显示自定义的定位点图标，则默认是脉冲式动画图
        
        XYLFindFreidlyModle *model = self.base_dataArry[self.count-1];
        [locationAnnotationView.headerImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
#if 0
        //定位点图标(用户自定义样式)
        locationAnnotationView.backImage = [UIImage imageNamed:@"found_image_positioning"];
        
#endif
#if 0
       // locationAnnotationView.backImage =
        //定位点图标(用户自定义样式)
       // locationAnnotationView.backImage = [UIImage imageNamed:@"img_dot"];
        
#endif
       // locationAnnotationView.headerImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_dot"]];
       // typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
       
#if 0
        //添加泡泡(自定义样式)
        XYLPaoPaoView *view = (XYLPaoPaoView *)[locationAnnotationView setupItemAnnotationIsCanViewtitle:annotation.title subtitle:annotation.subtitle];
        
        BMKActionPaopaoView *paopaoView = [[BMKActionPaopaoView alloc] initWithCustomView:view];
        
        locationAnnotationView.paopaoView = paopaoView;
#endif
        return locationAnnotationView;
     
    }else if ([annotation isKindOfClass:[XYLClusterAnnotation class]]){
        //普通annotation
        NSString *AnnotationViewID = @"ClusterMark";
        XYLClusterAnnotation *cluster = (XYLClusterAnnotation *)annotation;
        
        XYLClusterAnnotationView *annotationView = [[XYLClusterAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        
        annotationView.size = cluster.size;
        
        annotationView.draggable = YES;
        
        annotationView.annotation = cluster;
        
        return annotationView;
        
    };
    
#endif
    return nil;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    XYLLog(@"选中哪一行的annotationView");
    if ([view isKindOfClass:[XYLLocationAnnotationView class]]) {
        XYLLog(@"选中哪一行的annotationView");
    }
}

/**
 *地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）都会调用此接口
 *@param mapView 地图View
 *@param status 此时地图的状态
 */
- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus *)status {
    
    CLLocationCoordinate2D coordinate2D;
    
    coordinate2D = status.targetGeoPt;
    
    NSLog(@"经络==%f,纬络==%f",coordinate2D.latitude,coordinate2D.longitude);
    
    if (_clusterZoom != 0 && _clusterZoom != (NSInteger)mapView.zoomLevel) {
        //地理中点
        
        NSLog(@"经络==%f,纬络==%f",coordinate2D.latitude,coordinate2D.longitude);
        
        [self updateClusters];
    }
}


int RememberSelectedIndex;
//选中哪一行
- (void)selectedAnnotationViewWithIndex:(UIButton *)selecteBtn{
    NSLog(@"选中第%ld个大头针",(selecteBtn.tag-1));
    
    
    if (!selecteBtn.selected) {
        NSLog(@"选中选中选中选中选中");
        
        selecteBtn.selected = !selecteBtn.selected;
    }
    
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"HHFindViewController" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
